** Building instrument for market size growth (across cells of the product space)
global db "D:\Dropbox\unequal_gains\main_data"
global Section4 "D:\Dropbox\unequal_gains\QJE revision plan\analysis\section4_data"

use "$Section4/age_educ_race_children_state_groups_final", clear
rename statefip fips_state_code
merge 1:m fips_state_code age_bin education race children using "$Section4/age_educ_race_children_state_shares"
keep if _merge==3

bysort product_module_code quality_rank: egen double spending_l=sum(total_spending)
gen double s_nl=total_spending/spending_l

* build instruments using raw &  residualized shocks
gen double inst_raw = g_n_annual*s_nl
foreach i in linageres ageres ageeducres ageeducstateres allres ///
educres stateres linageducres linagestateres linagerace linagechild raceres childrenres {
gen double inst_`i' = g_n_annual_`i'*s_nl
}

collapse (sum) inst_* total_spend, by(product_module_code quality_rank) fast
rename total_spend total_spend_HMS0406

save "$Section4/instrument_age_educ_race_children_state", replace
